package com.wdf.rule.dynamic;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author moon
 * @date 2023-02-15 20:50
 * @since 1.8
 */
public class CustomClassLoader extends ClassLoader{

    /**
     * 缓存源代码对象
     */
    private Map<String, CustomJavaFileObject> fileCacheMap = new ConcurrentHashMap<>(16);

    /**
     * 初始化类加载器
     * @param parent
     */
    public CustomClassLoader(ClassLoader parent) {
        super(parent);
    }

    /**
     * 添加源码缓存
     * @param obj
     */
    public void addJavaCode(CustomJavaFileObject obj) {
        fileCacheMap.put(obj.getName(), obj);
    }

    /**
     * 获取类
     * @param className
     *          The <a href="#binary-name">binary name</a> of the class
     *
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        if (fileCacheMap.containsKey(className)){
            byte[] byteCode = fileCacheMap.get(className).getByteCode();
            return defineClass(className, byteCode, 0, byteCode.length);
        } else {
            return super.findClass(className);
        }
    }
}

